package com.kirk.cts.core.loader;

import com.kirk.cts.core.context.CrawlerToolContextData;
import com.kirk.cts.core.utils.PropertiesHelper;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * <p> PluginsLoader.java </p>
 *
 * @version 1.0.0
 * @Author kirkliu
 * @Date 2020-08-29 22:23
 * @Description 加载系统插件
 */
public class PluginsLoader {

    private static Logger log = Logger.getLogger(PluginsLoader.class);
    /**
     * 爬虫配置参数文件路径
     */

    private static String CRAWLER_PLUGINS_PATH = "/plugins/CrawlerToolPlugins.properties";


    public static void loadPlugins() {
        log.info("开始加载系统插件配置文件:" + CRAWLER_PLUGINS_PATH);

        PropertiesHelper propertiesHelper = new PropertiesHelper();
        Properties properties = propertiesHelper.loadProperties(CRAWLER_PLUGINS_PATH);
        Enumeration<?> propNames = properties.propertyNames();
        String propKey = null;
        String propValue = null;
        Map<String, Map<String, String>> plugins = new HashMap<String, Map<String, String>>();
        while (propNames.hasMoreElements()) {
            propKey = (String) propNames.nextElement();
            propValue = properties.getProperty(propKey);
            log.info("加载插件：" + propKey + ",插件路径为：" + propValue);
            if (StringUtils.isNotBlank(propKey) && StringUtils.isNotBlank(propValue)) {
                plugins.put(propKey, propertiesHelper.propertiesToMap(propValue));
            }
        }
        CrawlerToolContextData.getInstance().setPlugins(plugins);
        log.info("加载系统插件置文件加载完成");
    }

}
